/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.service.impl;

import lombok.RequiredArgsConstructor;
import me.zhengjie.domain.KwExamTeacher;
import me.zhengjie.domain.KwMasterTearcher;
import me.zhengjie.mapper.DeptMapper;
import me.zhengjie.mapper.ExamTeacherMapper;
import me.zhengjie.mapper.SysUsersRolesMapper;
import me.zhengjie.mapper.UserMapper;
import me.zhengjie.pojo.entity.ExamTeacher;
import me.zhengjie.pojo.entity.User;
import me.zhengjie.repository.KwExamRepository;
import me.zhengjie.repository.KwExamTeacherRepository;
import me.zhengjie.repository.KwMasterTearcherRepository;
import me.zhengjie.repository.KwOccupyRepository;
import me.zhengjie.service.KwExamTeacherService;
import me.zhengjie.service.dto.KwExamTeacherDto;
import me.zhengjie.service.dto.KwExamTeacherQueryCriteria;
import me.zhengjie.service.mapstruct.KwExamTeacherMapper;
import me.zhengjie.util.KwUtils;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author LongYang
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2021-06-28
 **/
@Service
@RequiredArgsConstructor
public class KwExamTeacherServiceImpl implements KwExamTeacherService {

    private final KwExamTeacherRepository kwExamTeacherRepository;
    private final KwExamTeacherMapper kwExamTeacherMapper;
    private final KwOccupyRepository kwOccupyRepository;
    private final KwMasterTearcherRepository kwMasterTearcherRepository;
    private final KwExamRepository kwExamRepository;
    private final UserMapper userMapper;
    private final SysUsersRolesMapper sysUsersRolesMapper;

    private final DeptMapper deptMapper;
    private final ExamTeacherMapper examTeacherMapper;
    private final KwUtils kwUtils;

    @Override
    public Map<String, Object> queryAll(KwExamTeacherQueryCriteria criteria, Pageable pageable) {

        Set<Long> roles = kwUtils.getRoles();
        User user = kwUtils.getUser();
        Set<Integer> examIds = kwUtils.getExamIds();
        //是否考试管理员
        boolean isExam = false;
        //是否部门管理员
        boolean isDept = false;
        //是否系统管理员
        boolean isAdmin = false;
        //是否本考试的部门管理员
        boolean isExamDept = true;
        for (Integer examId : examIds) {
            if (Objects.equals(criteria.getExamId(),examId)) {
                isExamDept = false;
            }
        }

        for (Long roleId : roles) {
            if (Objects.equals(roleId, 5L)) {
                isExam = true;
            }
            if (Objects.equals(roleId, 6L)) {
                isDept = true;
            }
            if (Objects.equals(roleId, 1L)) {
                isAdmin = true;
            }
        }
        List<ExamTeacher> list = examTeacherMapper.findPage(criteria, pageable.getPageNumber(), pageable.getPageSize(), user.getDeptId(), isExam, isDept, user.getUserId(), isAdmin,isExamDept);
        Integer count = examTeacherMapper.findCount(criteria, pageable.getPageNumber(), pageable.getPageSize(), user.getDeptId(), isExam, isDept, user.getUserId(), isAdmin,isExamDept);
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", list);
        map.put("totalElements", count == null ? 0 : count);
        return map;

//        String alias = criteria.getAlias();
//        String checkinStatus = criteria.getCheckinStatus();
//        String delFlag = criteria.getDelFlag();
//        Integer deptId = criteria.getDeptId();
//        Integer examId = criteria.getExamId();
//        Integer examRoomId = criteria.getExamRoomId();
//        Integer id = criteria.getId();
//        String idCard = criteria.getIdCard();
//        String identity = criteria.getIdentity();
//        String jobNumber = criteria.getJobNumber();
//        String nameCn = criteria.getNameCn();
//        String phone = criteria.getPhone();
//        Integer roomId = criteria.getRoomId();
//        Integer sex = criteria.getSex();
//        Integer teacherId = criteria.getTeacherId();
//        String type = criteria.getType();
//        User user = userMapper.selectById(SecurityUtils.getCurrentUserId());
//        /*获取用户角色*/
//        QueryWrapper<SysUsersRoles> usersRolesQueryWrapper = new QueryWrapper<>();
//        usersRolesQueryWrapper.eq("user_id", user.getUserId())
//                .eq("role_id", 1);
//        List<SysUsersRoles> sysUsersRoles = sysUsersRolesMapper.selectList(usersRolesQueryWrapper);
//        PredicateBuilder<KwExamTeacher> builder = Specifications.<KwExamTeacher>and()
//                .eq(id != null, "id", id)
//                .eq(examRoomId != null, "examRoomId", examRoomId)
//                .like(StringUtils.isNotBlank(jobNumber), "jobNumber", "%" + jobNumber + "%")
//                .like(StringUtils.isNotBlank(nameCn), "nameCn", "%" + nameCn + "%")
//                .eq(StringUtils.isNotBlank(idCard), "idCard", idCard)
//                .like(StringUtils.isNotBlank(alias), "alias", "%" + alias + "%")
//                .eq(teacherId != null, "teacherId", teacherId)
//                .eq(roomId != null, "roomId", roomId)
//                .eq(deptId != null, "deptId", deptId)
//                .eq(StringUtils.isNotBlank(type), "type", type)
//                .eq(StringUtils.isNotBlank(delFlag), "delFlag", delFlag)
//                .like(StringUtils.isNotBlank(phone), "phone", "%" + phone + "%")
//                .eq(examId != null, "examId", examId)
//                .eq(StringUtils.isNotBlank(identity), "identity", identity)
//                .eq(StringUtils.isNotBlank(checkinStatus), "checkinStatus", checkinStatus)
//                .eq(sex != null, "sex", sex);
//        /*如果用户不是超级管理员那么只查询出他自己部门的教师*/
//        if (sysUsersRoles == null || sysUsersRoles.isEmpty()) {
//            builder.eq("saveDeptId", user.getDeptId());
//        }
//        Specification<KwExamTeacher> specification = builder.build();
//        Page<KwExamTeacher> page = kwExamTeacherRepository.findAll(specification, pageable);
//
//        for (KwExamTeacher kwExamTeacher : page.getContent()) {
//            if (kwExamTeacher.getDeptId() != null) {
//                Dept dept = deptMapper.selectById(kwExamTeacher.getDeptId());
//                if (dept != null) kwExamTeacher.setDeptName(dept.getName());
//            }
//        }
    }

    @Override
    public List<KwExamTeacherDto> queryAll(KwExamTeacherQueryCriteria criteria) {
        return kwExamTeacherMapper.toDto(kwExamTeacherRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public KwExamTeacherDto findById(Integer id) {
        KwExamTeacher kwExamTeacher = kwExamTeacherRepository.findById(id).orElseGet(KwExamTeacher::new);
        ValidationUtil.isNull(kwExamTeacher.getId(), "KwExamTeacher", "id", id);
        return kwExamTeacherMapper.toDto(kwExamTeacher);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public KwExamTeacherDto create(KwExamTeacher resources) {
        /*Optional<KwExam> kwExam = kwExamRepository.findById(resources.getExamId());
        if (kwExam.isPresent()) {
            kwExam.get("");
        }*/
        User user = userMapper.selectById(SecurityUtils.getCurrentUserId());
        resources.setSaveDeptId(user != null ? user.getDeptId() : null);

        return kwExamTeacherMapper.toDto(kwExamTeacherRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(KwExamTeacher resources) {
        KwExamTeacher kwExamTeacher = kwExamTeacherRepository.findById(resources.getId()).orElseGet(KwExamTeacher::new);
        ValidationUtil.isNull(kwExamTeacher.getId(), "KwExamTeacher", "id", resources.getId());
        kwExamTeacher.copy(resources);
        kwExamTeacherRepository.save(kwExamTeacher);
        /*根据id查询该教师修改身份*/
        Optional<KwMasterTearcher> masterTearcher = kwMasterTearcherRepository.findById(resources.getTeacherId());
        if (masterTearcher.isPresent()) {
            KwMasterTearcher tearcher = masterTearcher.orElse(null);
            if (!tearcher.getIdentity().contains(resources.getIdentity())) {
                tearcher.setIdentity(tearcher.getIdentity() + resources.getIdentity());
                kwMasterTearcherRepository.save(tearcher);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            KwExamTeacher kwExamTeacher = kwExamTeacherRepository.findFirstById(id);
            Integer examId = kwExamTeacher.getExamId();
            Integer typeId = kwExamTeacher.getTeacherId();
            kwOccupyRepository.deleteByExamIdAndTypeId(examId, typeId);
            kwExamTeacherRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<KwExamTeacherDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (KwExamTeacherDto kwExamTeacher : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("考场id", kwExamTeacher.getExamRoomId());
            map.put("教室工号", kwExamTeacher.getJobNumber());
            map.put("姓名", kwExamTeacher.getNameCn());
            map.put("身份证", kwExamTeacher.getIdCard());
            map.put("标识", kwExamTeacher.getAlias());
            map.put("教师id", kwExamTeacher.getTeacherId());
            map.put("部门id", kwExamTeacher.getDeptId());
            map.put("监考教师类型（0：上报，1：报名）", kwExamTeacher.getType());
            map.put("删除标识（0：未删除，1：已删除）", kwExamTeacher.getDelFlag());
            map.put("手机号", kwExamTeacher.getPhone());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}